<template>
  <el-divider v-if="border" class="m-0"></el-divider>
  <el-footer class="flex items-end justify-end px-0 select-none">
    <slot></slot>
    <el-pagination
      v-model:current-page="state.page"
      v-model:page-size="state.limit"
      :page-sizes="pageSizes"
      :disabled="disabled"
      :background="background"
      :class="`align-${align}`"
      layout="total,sizes,prev,pager,next,jumper"
      :total="total"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />
  </el-footer>
</template>

<script setup lang="ts">
import type { TableInstance } from 'element-plus'

import { pageSizes } from '@/config'

interface IProps {
  page: number
  limit: number
  offset: number
  total: number
  border?: boolean
  align?: 'right' | 'left' | 'between'
  disabled?: boolean
  background?: boolean
  tableRef?: Ref<TableInstance>
}
const props = withDefaults(defineProps<IProps>(), {
  border: true,
  disabled: false,
  background: false,
  align: 'right',
  total: 0,
  offset: 0
})

interface IEmit {
  (event: 'change'): void
  (event: 'update:page', value: number): void
  (event: 'update:limit', value: number): void
  (event: 'update:offset', value: number): void
}
const emit = defineEmits<IEmit>()

const state = reactive({
  page: useVModel(props, 'page', emit),
  limit: useVModel(props, 'limit', emit),
  offset: useVModel(props, 'offset', emit)
})
/**
 * 分页数据改变（page，limit发生变化都会出发），如果有table实例，则重置表格滚动高度
 */
function handleChange() {
  emit('change')
  if (props.tableRef) {
    props.tableRef.value.setScrollTop(0)
  }
}
/**
 * 处理页码改变
 */
function handlePageChange(val: number) {
  emit('update:page', val)
  emit('update:offset', (val - 1) * (state.limit as number))
  handleChange()
}
/**
 * 处理分页大小改变
 */
function handleSizeChange(val: number) {
  state.page = 1
  emit('update:page', state.page)
  emit('update:limit', val)
  handleChange()
}

defineExpose({
  reset() {
    state.page = 1
    state.limit = 10
    state.offset = 0
  }
})
</script>

<style scoped lang="scss">
:deep(.el-pagination) {
  &[class*='align'] {
    @apply w-full;
  }

  @apply text-[12px] text-[#83858A];

  &.align-between {
    .el-pagination__jump {
      // @apply ml-auto;
    }

    .btn-prev {
      // @apply ml-auto;
    }
  }

  &.align-right {
    @apply ml-auto w-auto;
  }

  .el-pagination__total {
    color: #868d9d;
  }

  .btn-prev {
    @apply rounded-[4px];

    border: 1px solid #dbdde2;
  }

  .btn-next {
    @apply rounded-[4px];

    border: 1px solid #dbdde2;
  }

  .el-pager {
    @apply text-[#83858A] mx-[4px];

    .number {
      @apply rounded-[4px];

      border: 1px solid #dbdde2;
    }

    .number:not(:last-child) {
      margin-right: 4px;
    }

    .is-active {
      border-color: #164cff;
    }
  }

  .el-pagination__jump {
    @apply text-[#83858A];
  }
}
</style>
